define(function (require, exports, module) {
    var photoBrowser = api.require('photoBrowser');
    var UserInfo = _g.getLS('UserInfo');
    var Http = require('U/http');
    var weiXin = api.require('weiXin');
    var checkUserId = api && api.pageParam.checkUserId;
    var notNeedPay = api && api.pageParam.notNeedPay;
    var images = new Vue({
        el: '#images',
        template: _g.getTemplate('me/images-main-V'),
        data: {
            ownRedImgs: [],
            ownHideImgs: [],
            ownNormalImgs: [],
            otherRedImages: [{
                id: 0,
                imagePath: '',
                level: 2,
                checkPay: 3,
                checkStatus: true,
                createTime: '',
                updateTime: '',
            }],
            otherHideImages: [{
                id: 0,
                imagePath: '',
                level: 1,
                checkPay: 0,
                checkStatus: true,
                createTime: '',
                updateTime: '',
            }],
            otherNormalImgs: [{
                id: 0,
                imagePath: '',
                level: 0,
                checkPay: 0,
                checkStatus: true,
                createTime: '',
                updateTime: '',
            }],
            redList: [], // 红包图片备份
            hideList: [], // 即焚图片备份
            normalList: [], // 普通图片备份
            isOwnImgs: !checkUserId,
            isDelTap: false,
            notNeedPay: notNeedPay
        },
        created: function () {
            this.otherRedImages = [];
            this.otherHideImages = [];
            this.otherNormalImgs = []
        },
        methods: {
            delRed() {
                this.ownRedImgs = []
                saveRed();
            },
            delHide(index) {
                this.ownHideImgs.splice(index, 1);
                saveHide();
            },
            delNormal(index) {
                this.ownNormalImgs.splice(index, 1);
                saveNormal();
            },
            onHideImg: function (index) {
                if ($(event.target).closest('.ui-image-del').length > 0) {
                    this.readThenHidImgs.splice(index, 1);
                    this.hideList.splice(index, 1);
                    saveHide();
                } else {
                    var imageList = [images.readThenHidImgs[index].imagePath];
                    photoBrowserFn(imageList);
                }
            },
            onNormalImg: function (index) {
                if ($(event.target).closest('.ui-image-del').length > 0) {
                    this.normalImgs.splice(index, 1);
                    this.normalList.splice(index, 1);
                    saveNormal();
                } else {
                    var imageList = [images.normalImgs[index].imagePath];
                    photoBrowserFn(imageList);
                }
            },
            addRedImg: function () {
                _g.openPicActionSheet({
                    allowEdit: true,
                    suc: function (ret) {
                        postRedAvatar(ret.data);
                    }
                });
            },
            addHideImg: function () {
                if (this.ownHideImgs.length >= 9) {
                    _g.toast('最多9张');
                    return
                }
                _g.openPicActionSheet({
                    allowEdit: true,
                    suc: function (ret) {
                        postHideAvatar(ret.data);
                    }
                });
            },
            addNormalImg: function () {
                if (this.ownNormalImgs.length >= 9) {
                    _g.toast('最多9张');
                    return
                }
                _g.openPicActionSheet({
                    allowEdit: true,
                    suc: function (ret) {
                        postNormalAvatar(ret.data);
                    }
                });
            },
            openOwnImage(data, index) {
                var data = {
                    images: data,
                    placeholderImg: 'widget://res/img/apicloud.png',
                    bgColor: '#000',
                    activeIndex: index
                };
                photoBrowser.open(data, function (ret, err) {
                    if (ret) {
                        if (ret.eventType === 'click') {
                            photoBrowser.close()
                        }

                    } else {
                        _g.toast('图片打开失败')
                    }
                })
            },
            openOtherRedImage(data) {
                if (notNeedPay || data.checkStatus) {
                    photoBrowser.open({
                        images: [data.imagePath],
                        placeholderImg: 'widget://res/img/apicloud.png',
                        bgColor: '#000'
                    }, function (ret, err) {
                        if (ret) {
                            if (ret.eventType === 'click') {
                                photoBrowser.close()
                            }
                        } else {
                            _g.toast('图片打开失败')
                        }
                    });
                } else {
                    api && api.confirm({
                        msg: '红包图片需要支付金额查看',
                        buttons: ['确定', '取消']
                    }, function (ret, err) {
                        if (ret.buttonIndex === 1) {
                            getWechatOrder(data);
                        }
                    })
                }
            },
            openOtherHideImage(data) {
                if (data.checkStatus) {
                    var time = UserInfo.identity === 1 ? 6000 : 2000;
                    photoBrowser.open({
                        images: [data.imagePath],
                        placeholderImg: 'widget://res/img/apicloud.png',
                        bgColor: '#000'
                    }, function (ret, err) {
                        if (ret) {
                            Http.ajax({
                                data: {
                                    userId: checkUserId,
                                    viewerId: UserInfo.id,
                                    photoId: data.id,
                                    type: 1
                                },
                                isSync: false,
                                url: '/photoViewer/save',
                                success: function (ret) {
                                    if (ret.code == 200) {
                                        setTimeout(function () {
                                            photoBrowser.close()
                                            data.checkStatus = false
                                        }, time);
                                    } else _g.toast('阅后即焚图片标记失败：' + ret.msg)
                                },
                                error(err) {
                                    _g.toast('阅后即焚图片标记错误：' + ret.msg)
                                }
                            });
                            if (ret.eventType === 'click') {
                                Http.ajax({
                                    data: {
                                        userId: UserInfo.id,
                                        viewerId: checkUserId,
                                        photoId: data.id,
                                        type: 1
                                    },
                                    isSync: false,
                                    url: '/photoViewer/save',
                                    success: function (ret) {
                                        if (ret.code == 200) {
                                            photoBrowser.close()
                                        } else _g.toast('阅后即焚图片标记失败：' + ret.msg)
                                    },
                                    error(err) {
                                        _g.toast('阅后即焚图片标记错误：' + ret.msg)
                                    }
                                });

                            } else {
                                // todo 调用阅后即焚接口
                            }

                        } else {
                            _g.toast('图片打开失败')
                        }
                    })
                }

            },
            openOtherNormalImage(index) {
                var imageList = [];
                this.otherNormalImgs.forEach(function (ele) {
                    imageList.push(ele.imagePath)
                })
                photoBrowser.open({
                    images: imageList,
                    placeholderImg: 'widget://res/img/apicloud.png',
                    bgColor: '#000',
                    activeIndex: index
                }, function (ret, err) {
                    if (ret) {
                        if (ret.eventType === 'click') {
                            photoBrowser.close()
                        }

                    } else {
                        _g.toast('图片打开失败')
                    }
                })
            },
        },
    });

    function getWechatOrder(redImg) {
        Http.ajax({
            data: {
                userId: UserInfo.id,
                payMoney: 1
            },
            isSync: true,
            url: '/pay/getWxPayOrder',
            success: function (ret) {
                if (ret.code == 200) {
                    postWechatRecharge(ret.data, redImg);
                } else {
                    alert(_g.j2s(ret));
                }
            }
        });
    };

    // 调起微信支付
    function postWechatRecharge(data, redImg) {
        weiXin.payOrder({
            key: data.appid,
            orderId: data.prepayid,
            partnerId: data.partnerid,
            nonceStr: data.noncestr,
            timeStamp: data.timestamp,
            sign: data.sign,
            package: data.package
        }, function (ret, err) {
            if (ret.status) {
                Http.ajax({
                    data: {
                        userId: checkUserId,
                        viewerId: UserInfo.id,
                        photoId: redImg.id,
                        type: 2
                    },
                    isSync: false,
                    url: '/photoViewer/save',
                    success: function (ret) {
                        if (ret.code == 200) {
                            redImg.checkStatus = true
                        } else _g.toast('查看' + ret.msg)
                    },
                    error(err) {
                        _g.toast('阅后即焚图片标记错误：' + ret.msg)
                    }
                });
                // _g.toast('充值成功');
            } else {
                api.alert('支付失败');
            }
        });
    };

    function checkHidePhoto(data, callback) {
        Http.ajax({
            data: {
                userId: UserInfo.id,
                viewerId: checkUserId,
                photoId: data.id
            },
            isSync: false,
            url: '/photoViewer/save',
            success: function (ret) {
                if (ret.code == 200) {
                    setTimeout(function () {
                        callback()
                    }, 2000);
                } else _g.toast('阅后即焚图片标记失败：' + ret.msg)
            },
            error(err) {
                _g.toast('阅后即焚图片标记错误：' + ret.msg)
            }
        });
    }

    function saveRed(data) {
        var imagePath = ''
        if (data) imagePath = data
        Http.ajax({
            data: {
                userId: UserInfo.id,
                level: 2,
                checkPay: 3,
                imagePath: imagePath
            },
            isSync: false,
            url: '/userPhoto/saveUserPhoto',
            success: function (ret) {
                if (ret.code == 200) {
                    if (images.isDelTap) images.redpacketImgs = []
                } else _g.toast('保存失败：' + ret.msg)
                this.isDelTap = false
            },
            error(err) {
                _g.toast('保存红包图片失败：' + err.msg)
                this.isDelTap = false
            }
        });
    };

    function saveHide() {
        var image_list = [].concat(images.ownHideImgs);
        if (!image_list.length) image_list = ''
        else image_list = image_list.join(',')
        Http.ajax({
            data: {
                userId: UserInfo.id,
                level: 1,
                checkPay: 0,
                imagePath: image_list
            },
            isSync: false,
            url: '/userPhoto/saveUserPhoto',
            success: function (ret) {},
            error(err) {
                _g.toast('保存阅后即焚图片失败：' + err.msg)
            }
        });
    };

    function saveNormal() {
        var image_list = [].concat(images.ownNormalImgs);
        if (!image_list.length) image_list = ''
        else image_list = image_list.join(',')
        Http.ajax({
            data: {
                userId: UserInfo.id,
                level: 0,
                checkPay: 0,
                imagePath: image_list
            },
            isSync: false,
            url: '/userPhoto/saveUserPhoto',
            success: function (ret) {
                if (ret.code == 200) {} else _g.toast('保存失败：' + ret.msg)
            },
            error(err) {
                _g.toast('保存普通图片失败：' + err.msg)
            }
        });
    };

    function postRedAvatar(img) {
        api.ajax({
            url: CONFIG.HOST + '/common/uploadPhoto',
            method: 'post',
            isSync: true,
            data: {
                values: {
                    token: UserInfo.token
                },
                files: {
                    image: img,
                }
            }
        }, function (ret, err) {
            if (ret.code == 200) {
                saveRed(ret.data);
                images.ownRedImgs.push(ret.data);
            } else {
                _g.toast(ret.msg);
            }
        });
    }

    function postHideAvatar(img) {
        api.ajax({
            url: CONFIG.HOST + '/common/uploadPhoto',
            method: 'post',
            isSync: true,
            data: {
                values: {
                    token: UserInfo.token
                },
                files: {
                    image: img,
                }
            }
        }, function (ret, err) {
            if (ret.code == 200) {
                images.ownHideImgs.push(ret.data)
                saveHide();
            } else {
                _g.toast(ret.msg);
            }
        });
    }

    function postNormalAvatar(img) {
        api.ajax({
            url: CONFIG.HOST + '/common/uploadPhoto',
            method: 'post',
            isSync: true,
            data: {
                values: {
                    token: UserInfo.token
                },
                files: {
                    image: img,
                }
            }
        }, function (ret, err) {
            if (ret.code == 200) {
                images.ownNormalImgs.push(ret.data);
                saveNormal();
            } else {
                _g.toast(ret.msg);
            }
        });
    }
    // 获取个人图库
    function getData() {
        Http.ajax({
            data: {
                userId: checkUserId || UserInfo.id,
                viewerId: UserInfo.id
            },
            isSync: false,
            url: '/userPhoto/getUserPhoto',
            success: function (ret) {
                // alert(_g.j2s(ret));
                if (ret.code == 200) {
                    var data = ret.data;
                    if (!checkUserId) {
                        data.forEach(function (ele) {
                            if (ele.level === 2 && ele.imagePath !== '') images.ownRedImgs.push(ele.imagePath)
                            else if (ele.level === 1 && ele.imagePath !== '') images.ownHideImgs.push(ele.imagePath)
                            else if (ele.level === 0 && ele.imagePath !== '') images.ownNormalImgs.push(ele.imagePath)
                        });
                    } else {
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].level === 2 && data[i].imagePath !== '') images.otherRedImages.push(data[i])
                            else if (data[i].level === 1 && data[i].imagePath !== '') images.otherHideImages.push(data[i])
                            else if (data[i].level === 0 && data[i].imagePath !== '') images.otherNormalImgs.push(data[i])

                        }
                    }

                }
            }
        });
    };

    getData();

    module.exports = {};

});